package server

import (
	"dake-farmer-home/internal/models"
	"dake-farmer-home/internal/pkg/configs"
	"dake-farmer-home/internal/pkg/gormlogs"
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/gorm"
	"log/slog"
	"time"
)

func Init() {
	InitConfig()
	InitDB()
	NewServer()

}

func InitDB() {

	gormConf := &gorm.Config{
		Logger: gormlogs.New(
			gormlogs.SetLogLevel(gormlogs.SlowQueryLogType, slog.LevelWarn),
			gormlogs.WithSlowThreshold(time.Second),
		),
	}

	if err := configs.Open(configs.Instance.DB, gormConf, models.Models...); err != nil {
		slog.Error(err.Error(), slog.Any("error", err))
	}

}

func InitConfig() {
	viper.SetConfigType("yaml")
	viper.AddConfigPath(".")

	if err := viper.ReadInConfig(); err != nil {
		panic(fmt.Errorf("fatal error config file: %w", err))
	}

	if err := viper.Unmarshal(&configs.Instance); err != nil {
		panic(fmt.Errorf("fatal error config file: %w", err))
	}
}
